package cn.zy.framework.helper;

import cn.zy.framework.annotation.Action;
import cn.zy.framework.bean.Handler;
import cn.zy.framework.bean.Request;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author: Administrator
 * @Description:
 * @Date: Created in 10:17 2021/9/11
 * @Modified By:
 * @version: 1.0
 * 控制器助手类
 */
public class ControllerHelper {
	/**
	 * 存放请求与处理器的映射关系
	 */
	private static final Map<Request, Handler> ACTION_MAP = new HashMap<Request, Handler>();;

	static {
		//获取所有Controller 类
		Set<Class<?>> controllerClassSet = ClassHelper.getControllerClassSet();
		if (CollectionUtils.isNotEmpty(controllerClassSet)) {
			for (Class<?> controllerClass : controllerClassSet) {
				Method[] methods = controllerClass.getDeclaredMethods();
				if (ArrayUtils.isNotEmpty(methods)){
					for (Method method : methods) {
						if (method.isAnnotationPresent(Action.class)){
							//从Action 注解中获取URL 映射规则
							Action action = method.getAnnotation(Action.class);
							String mapping = action.value();
							//验证 URL 映射规则
							if (mapping.matches("\\w+:/\\w*")){
								String[] array = mapping.split(":");
								if (ArrayUtils.isNotEmpty(array) && array.length==2){
									//获取请求方法与路径
									String requestMethod = array[0];
									String requestPath = array[1];
									Request request = new Request(requestMethod, requestPath);

									Handler handler = new Handler(controllerClass, method);
									ACTION_MAP.put(request, handler);
								}
							}
						}
					}
				}
			}
		}
	}

	public static Handler getHandler(String requestMethod, String requestPath){
		Request request = new Request(requestMethod, requestPath);
		return ACTION_MAP.get(request);
	}

}
